import { Avatar, Button } from 'antd';
import React, { useMemo } from 'react';
import { useContextSelector } from 'use-context-selector';

import appService from '@/api/services/appService';
import { useRequest2 } from '@/hooks/use-request';
import { t } from '@/locales/i18n';
import { SelectAppItemType } from '@/types/workflow/template/system/abandoned/runApp/type';

import { WorkflowContext } from '../../../../../context';

import type { RenderInputProps } from '../type';

const SelectAppRender = ({ item, nodeId }: RenderInputProps) => {
  const filterAppIds = useContextSelector(WorkflowContext, (ctx) => ctx.filterAppIds);
  const onChangeNode = useContextSelector(WorkflowContext, (v) => v.onChangeNode);

  const value = item.value as SelectAppItemType | undefined;
  const { data: appDetail, loading } = useRequest2(
    () => {
      if (value?.id) return appService.getAppDetailById(value.id);
      return Promise.resolve(null);
    },
    {
      manual: false,
      refreshDeps: [value?.id],
      errorToast: 'Error',
      onError() {
        onChangeNode({
          nodeId,
          type: 'updateInput',
          key: 'app',
          value: {
            ...item,
            value: undefined,
          },
        });
      },
    },
  );

  const Render = useMemo(() => {
    return (
      <>
        {/* TODO */}
        {/* <div onClick={onOpenSelectApp}> */}
        <div>
          {!value ? (
            <Button style={{ width: '100%' }}>{t('core.module.Select app')}</Button>
          ) : (
            <Button
              loading={loading}
              className={`${loading ? 'justify-center' : 'justify-start'}`}
              style={{ width: '100%' }}
              // isLoading={loading}
              // w={'100%'}
              // justifyContent={loading ? 'center' : 'flex-start'}
              // variant={'whiteBase'}
              icon={<Avatar src={appDetail?.avatar} size={6} />}
            >
              {appDetail?.name}
            </Button>
          )}
        </div>
        {/* TODO */}
        {/* {isOpenSelectApp && (
          <SelectAppModal
            value={item.value}
            filterAppIds={filterAppIds}
            onClose={onCloseSelectApp}
            onSuccess={(e) => {
              onChangeNode({
                nodeId,
                type: 'updateInput',
                key: 'app',
                value: {
                  ...item,
                  value: e
                }
              });
            }}
          />
        )} */}
      </>
    );
  }, [appDetail?.avatar, appDetail?.name, loading, value]);

  return Render;
};

export default React.memo(SelectAppRender);
